﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Security.Cryptography;
using System.IO;
using System.Text;

using CE.Image;
using CE.User;
using CE.Mail;
using CE.Configuration;

public partial class PasswordRecovery : CE.Global.MyLanguageBasePage
{
    string _redirectUrl = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["ImageCount"] != null)
        {
            if (Convert.ToInt32(Session["ImageCount"].ToString()) > 5)
            {
                lblMessage.Text = "Please try after a few moment! Your session has been locked!";
                btnSubmit.Enabled = false;
                btnNewImage.Enabled = false;
                txtEmail.Enabled = false;
                txtSecurityCode.Enabled = false;
                Response.Redirect("usermessage.aspx?mt=UM&ec=1993");
            }
            else
            {
                lblMessage.Text = "";
                btnSubmit.Enabled = true;
                btnNewImage.Enabled = true;
                txtEmail.Enabled = true;
                txtSecurityCode.Enabled = true;
            }
        }

        if (!Page.IsPostBack)
        {
            txtEmail.Attributes.Add("onblur", "RemoveSpace(this);ShowValidationEffectTwo('" + txtEmail.ClientID + "','" + rfvEmail.ClientID + "','" + rfvEmailValid.ClientID + "');DefaultEmail(this, event);");
            txtEmail.Attributes.Add("onfocus", "ClearText(this, event);");

            Session["UMMSG"] = null;
            LogUserViewedHistory();
            GetCookies();

            if (Session["ImageCount"] != null)
            {
                if (Convert.ToInt32(Session["ImageCount"].ToString()) <= 5)
                {
                    CreateUpdateImageAndSession();
                }
            }
            else
            {
                CreateUpdateImageAndSession();
            }
        }
    }

    private void LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        _userviewdb.LogViewedHistory("PWR", Request, "User password recovery.");
    }

    private void CreateUpdateImageAndSession()
    {
        MyImage myimage = new MyImage();
        string salt = "";

        if (Session[CE.Global.General.SecurityCheckWord] != null)
        {
            salt = myimage.GetRandomWord(Session[CE.Global.General.SecurityCheckWord].ToString());
        }
        else
        {
            if (Session[CE.Global.General.SecurityCheckWord] != null)
            {
                salt = myimage.GetRandomWord(Session[CE.Global.General.SecurityCheckWord].ToString());
            }
            else
            {
                salt = myimage.GetRandomWord("all");
            }
        }
        Session[CE.Global.General.SecurityCheckWord] = salt;
        imgCAPTCHA.ImageUrl = @"CAPTCHA/CAPTCHAImageHandler.ashx?id=" + CE.Security.MySecurity.Encrypt(salt, true);
        txtSecurityCode.Text = "";
    }

    protected void btnNewImage_Click(object sender, EventArgs e)
    {
        CreateUpdateImageAndSession();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (Session[CE.Global.General.SecurityCheckWord] != null)
            {
                string _usrText = txtSecurityCode.Text.ToUpper();
                string _imgText = Session[CE.Global.General.SecurityCheckWord].ToString().ToUpper();
                if (_usrText == _imgText)
                {
                    AccountDB _accountdb = new AccountDB();
                    Account _account = _accountdb.GetUserAccount(txtEmail.Text, Convert.ToInt32(CE.Global.General.CEUserType.Customer));
                    if (_account != null)
                    {
                        string salt = CE.Security.MySecurity.Encrypt(Session[CE.Global.General.SecurityCheckWord].ToString(), true);
                        string strGUID = _accountdb.GetGUID(_account.CEID);
                        salt = salt.Replace("+", "");
                        _account.AuthSalt = salt;
                        if (_accountdb.Insert(_account) > 0)
                        {
                            if (MyMailManager.SendPasswordResetLink(_account.Email, _account.Email, salt, strGUID, CE.Global.General.CEUserType.Customer))
                            {
                                _redirectUrl = "usermessage.aspx";
                                Session["UMMSG"] = "UM,199";
                                Response.Redirect(_redirectUrl);
                            }
                            else
                            {
                               lblMessage.Text = "Can't send password recovery information to your email account.!";
                            }
                        }
                        else
                        {
                            lblMessage.Text = "Creating password recovery information failed!Try again later!";
                        }
                    }
                    else
                    {
                        lblMessage.Text = Resources.UserMessage.NoEmailFound;//"No such email found.!";
                    }
                }
                else
                {
                    lblMessage.Text = Resources.UserMessage.WrongSecurityCheck;//"Wrong security check!";
                    CreateUpdateImageAndSession();
                }
            }
            else
            {
                lblMessage.Text = "Security Check code was expired. Please try again.";
                CreateUpdateImageAndSession();
            }
        }
    }

    public string CreateSalt(int size)
    {
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        Byte[] buff = new Byte[size];
        rng.GetBytes(buff);

        return Convert.ToBase64String(buff);
    }

    private void GetCookies()
    {
        HttpCookie _cookie = Request.Cookies.Get("GGMobile_Quote");
        if (_cookie != null)
        {
            txtEmail.Text = CE.Security.MySecurity.Decrypt(_cookie.Values.Get("CustomerEmail"), true);
        }
    }
}
